﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace MCP.Util
{
    /// <summary>
    /// UDP Util wraps the UDP implementation to easily portable interface.
    /// </summary>
    public class UdpSocket : IDisposable
    {
        private UdpClient m_udpClient;

        /// <summary>
        /// Initializes udp socket with random local port in dynamic port range.
        /// </summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        public UdpSocket()
        {
            m_udpClient = new UdpClient();
        }

        /// <summary>
        /// Initializes udp socket to chosen local in endpoint.
        /// </summary>
        /// <param name="port"></param>
        public UdpSocket(IPEndPoint localEndPoint)
        {
            m_udpClient = new UdpClient(localEndPoint);
        }

        /// <summary>
        /// Sends bytes to given remote end point.
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="bytes"></param>
        /// <param name="length"></param>
        public void SendBytes(IPEndPoint remoteEndPoint, byte[] bytes, int length)
        {
            m_udpClient.Send(bytes, length, remoteEndPoint);
        }

        /// <summary>
        /// Receives bytes and stores remote end point information to the provided remote end point object.
        /// </summary>
        /// <param name="bytes"></param>
        public byte[] ReceiveBytes(IPEndPoint remoteEndPoint)
        {
            IPEndPoint receivedRemoteEndPoint=null;
            byte[] bytes=m_udpClient.Receive(ref receivedRemoteEndPoint);
            remoteEndPoint.Address = receivedRemoteEndPoint.Address;
            remoteEndPoint.Port = remoteEndPoint.Port;
            return bytes;
        }

        /// <summary>
        /// Disposes udp resources.
        /// </summary>
        public void Dispose()
        {
            m_udpClient.Close();
        }

    }
}
